package linkedlist;

/**
 *   给你链表的头结点 head ，请将其按 升序 排列并返回 排序后的链表
 */
public class no148 {
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode temp = slow.next;
        slow.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(temp);
        ListNode newNode = new ListNode(-1);
        ListNode cur = newNode;
        while (left != null && right != null){
            if(left.val <= right.val){
                cur.next = left;
                left = left.next;
                cur = cur.next;
            }else{
                cur.next = right;
                right = right.next;
                cur = cur.next;
            }
        }
        if (left == null){
            cur.next = right;
        }
        if (right == null){
            cur.next = left;
        }
        return newNode.next;
    }
}
